Page({
  data: {
    devices: [],
    currentBtn: 0,
    openBlueFlag: false,
    showSetting: true,
    icon1: '/image/icon1.png',
    icon2: '/image/icon2.png',
    icon3: '/image/icon3.png',
    icon4: '/image/icon4.png',
    icon5: '/image/icon5.png',
    file: {
      fileName: '',
      filePath: '',
      fileSize: '',
    },
    canBlue: false,
    currentImage: null
  },
  onLoad() {
    if (wx.getSystemInfoSync().platform !== 'android') {
      wx.showModal({
        title: '温馨提示!',
        content: '检测到您的设备为IOS系统，由于蓝牙兼容问题，设备升级较慢，建议更换安卓系统！',
        showCancel: false
      })
    }
  },
  onShow() {
    wx.getStorage({
      key: 'token',
      fail: (err) => {
        wx.navigateTo({
          url: '/pages/login/login',
        })
      }
    })
    wx.getStorage({
      key: 'Hex',
      success: (res) => {
        this.setData({
          "canBlue": true,
          "file.fileName": JSON.parse(res.data).name,
          "file.filePath": JSON.parse(res.data).path,
          "file.fileSize": JSON.parse(res.data).size
        })
      },
      fail: () => {
        this.setData({
          "canBlue": false,
          "file.fileName": '',
          "file.filePath": '',
          "file.fileSize": ''
        })
      }
    })
  },
  //选择文件按钮点击事件
  getUpdataFile(e) {
    let that = this
    if (e.target.dataset.type !== this.data.currentImage) {
      wx.chooseMessageFile({
        count: 1,
        type: 'file',
        extension: ['.hex', 'hex'], //此处限制文件类型
        success(res) {
          wx.showLoading({
            title: '加载中...'
          })
          wx.uploadFile({
            // url: 'http://192.168.8.241:18081/tenant/product/convert', // 开发者服务器接口地址
            url: 'https://gysys.ori-dxe.com/api/tenant/product/convert', // 开发者服务器接口地址
            filePath: res.tempFiles[0].path, // 要上传文件资源的路径
            name: 'file', // 文件对应的 key
            success: uploadResult => {
              wx.downloadFile({
                url: JSON.parse(uploadResult.data).data,
                success: (e) => {
                  wx.setStorage({
                    key: 'Hex',
                    data: JSON.stringify(res.tempFiles[0]),
                    success: () => {
                      wx.hideLoading()
                      wx.setStorage({
                        key: 'Hex2',
                        data: e.tempFilePath,
                      })
                      that.setData({
                        "canBlue": true,
                        "file.fileName": res.tempFiles[0].name,
                        "file.filePath": res.tempFiles[0].path,
                        "file.fileSize": res.tempFiles[0].size
                      })
                    }
                  })
                },
                fail: (err) => {
                  wx.hideLoading()
                  wx.showToast({
                    title: '下载失败',
                    icon: 'none'
                  })
                }
              })

            },
            fail: uploadError => {
              wx.hideLoading()
              // 处理上传失败的错误
              console.error(uploadError);
              wx.showToast({
                title: '上传失败',
                icon: 'error'
              })
            }
          });

        }
      })
    }
  },
  // 1.初始化蓝牙
  openBluetoothAdapter() {
    wx.showLoading({
      title: '搜索中...',
    })
    var that = this
    if (this.data.openBlueFlag) {
      this.closeBluetoothAdapter()
    }
    this.setData({
      currentBtn: 1,
      openBlueFlag: true,
      devices: [],
      connected: false
    })
    wx.openBluetoothAdapter({
      success: (res) => {
        //判断是iOS还是Android，Android需获取是否授权定位
        if (wx.getSystemInfoSync().platform === 'android') {
          this.isLocationEnabled()
        } else {
          this.getBluetoothAdapterState()
        }
      },
      fail: (res) => {
        wx.hideLoading()
        this.setData({
          currentBtn: 0,
        })
        if (wx.getSystemInfoSync().platform === 'android') {
          wx.showToast({
            title: '请打开蓝牙及定位！',
            icon: 'none',
            image: '/image/warning.png',
            duration: 3000
          })
        } else {
          wx.showToast({
            title: '请打开蓝牙！',
            icon: 'none',
            image: '/image/warning.png',
            duration: 3000
          })
        }
      }
    })
    //监听蓝牙适配器状态变化事件
    wx.onBluetoothAdapterStateChange(function (res) {
      var isDvailable = res.available; //蓝牙适配器是否可用
      if (isDvailable) {
        that.startBluetoothDevicesDiscovery();
      } else {
        that.stopBluetoothDevicesDiscovery(true); //停止搜索
        that.setData({
          devices: [],
          currentBtn: 0
        });
        wx.showToast({
          title: '蓝牙未打开',
          icon: 'none',
          image: '/image/warning.png',
          duration: 2000
        })
      }
    })
  },
  // 2.获取适配器状态
  getBluetoothAdapterState() {
    wx.getBluetoothAdapterState({
      success: (res) => {
        console.log('适配器状态', res);
        if (res.discovering) {
          this.onBluetoothDeviceFound()
        } else if (res.available) {
          this.startBluetoothDevicesDiscovery()
        }
      }
    })
  },
  // 3.开始搜索蓝牙
  startBluetoothDevicesDiscovery() {
    wx.showLoading({
      title: '搜索中...',
    })
    if (this._discoveryStarted) {
      wx.hideLoading()
      return
    }
    this._discoveryStarted = true
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {
        this.onBluetoothDeviceFound()
      },
    })
  },
  // 4.搜索到的设备显示到页面上
  onBluetoothDeviceFound() {
    wx.onBluetoothDeviceFound((res) => {
      console.log('设备', res);
      res.devices.forEach(device => {
        if (device.localName) { //&& device.name
          if (device.localName.length != 19 && device.localName.slice(12) != 'BC1428M' && device.localName.slice(12) != 'BD1428M' && device.localName.slice(12) != 'BC1468G' && device.localName.slice(12) != 'BD1468G') {
            return
          }
          // if (device.name.length != 19 && device.name.slice(12) != 'BC1428M' && device.name.slice(12) != 'BD1428M' && device.name.slice(12) != 'BC1468G' && device.name.slice(12) != 'BD1468G') {
          //   return
          // }
        }
        if (!device.localName) { //!device.name && 
          return
        }
        if (device.localName.slice(12) == 'BC1428M' || device.localName.slice(12) == 'BD1428M') {
          device.name = `电表--${device.localName.slice(0,12)}`
        } else if (device.localName.slice(12) == 'BC1468G' || device.localName.slice(12) == 'BD1468G') {
          device.name = `水表--${device.localName.slice(0,12)}`
        }
        console.log('设备信息', device);
        const foundDevices = this.data.devices
        const idx = inArray(foundDevices, 'deviceId', device.deviceId)
        const data = {}
        if (idx === -1) {
          data[`devices[${foundDevices.length}]`] = device
        } else {
          data[`devices[${idx}]`] = device
        }
        this.setData(data)
      })
    })
  },
  // 5.点击蓝牙并创建连接
  createBLEConnection(e) {
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const name = ds.name
    wx.showLoading({
      title: '正在连接...',
    })
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        this.stopBluetoothDevicesDiscovery(false)
        wx.hideLoading()
        this.setData({
          connected: true,
          name,
          deviceId,
          devices: []
        })
        wx.showToast({
          title: '连接成功',
          icon: 'success',
          duration: 1000
        })
        wx.navigateTo({
          url: `../connect/index?deviceId=${deviceId}&name=${name}`
        })
      },
      fail(err) {
        console.log(err);
        wx.hideLoading()
        wx.showToast({
          title: '连接失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  // 6.停止蓝牙搜索
  stopBluetoothDevicesDiscovery(flag) {
    wx.hideLoading()
    if (flag) {
      wx.showLoading({
        title: '正在停止',
        icon: 'none',
        duration: 1000
      })
    }
    wx.stopBluetoothDevicesDiscovery()
    this.setData({
      currentBtn: 0
    })
  },
  // 7.关闭蓝牙适配
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter()
    this._discoveryStarted = false
    this.setData({
      openBlueFlag: false
    })
  },
  //获取蓝牙授权状态
  getBluetoothAuth() {
    const that = this
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.bluetooth']) {
          that.openBluetoothAdapter()
        } else {
          wx.authorize({
            scope: 'scope.bluetooth',
            success() {
              that.openBluetoothAdapter()
            },
            fail() {
              that.setData({
                showSetting: false,
                showText: '需要您授权小程序使用蓝牙，否则无法连接设备'
              })
            }
          });
        }
      }
    });
  },
  //Android获取定位授权状态
  isLocationEnabled() {
    const that = this
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              wx.getLocation({
                success() {
                  // 成功获取到用户位置信息
                  that.getBluetoothAdapterState()
                },
                fail() {
                  that.setData({
                    currentBtn: 0
                  })
                  wx.showToast({
                    title: '请打开定位！否则无法搜索到设备',
                    icon: 'none',
                    image: '/image/warning.png',
                    duration: 2000
                  })
                }
              })
            },
            fail() {
              // 授权失败，处理错误情况
              that.setData({
                showSetting: false,
                showText: '需要您授权小程序使用定位，否则无法连接设备'
              })
            }
          })
        } else {
          wx.getLocation({
            success() {
              // 成功获取到用户位置信息
              that.getBluetoothAdapterState()
            },
            fail() {
              that.setData({
                currentBtn: 0
              })
              wx.showToast({
                title: '请打开定位！否则无法搜索到设备',
                icon: 'none',
                image: '/image/warning.png',
                duration: 2000
              })
            }
          })
        }
      }
    });
  },
  settingConfirm() {
    const that = this
    wx.openSetting({
      success() {
        that.setData({
          showSetting: true,
        })
        that.getBluetoothAuth()
      }
    })
  },
  settingCancel() {
    this.setData({
      showSetting: true,
    })
  },
})

function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}
//ArrayBuffer转换成16进制
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2))
  return hexArr.join('');
}